# -*- coding: utf-8 -*-
"""
@File:    oss.py
@Author:  jk.dong
@Desc:    OSS云存储模块
"""
import logging


class S3Client:
    _isinstance = None

    def __new__(cls, *args, **kwargs):
        if cls._isinstance is None:
            cls._isinstance = object.__new__(cls)
            return cls._isinstance
        else:
            return cls._isinstance

    def __init__(self, oss_config):
        import boto3
        self.s3 = boto3.resource(service_name=oss_config.get('oss_name'),
                                 aws_access_key_id=oss_config.get('access_key_id'),
                                 aws_secret_access_key=oss_config.get('secret_access_key'),
                                 endpoint_url=oss_config.get('endpoint_url'))

    # 创建bucket
    def create_bucket(self, bucketname):
        try:
            response = self.s3.create_bucket(Bucket=bucketname)
            return response["ResponseMetadata"]["HTTPStatusCode"]
        except Exception as err:
            logging.error(err)

    def delete_bucket(self, bucketname):
        try:
            response = self.s3.delete_bucket(Bucket=bucketname)
            return response["ResponseMetadata"]["HTTPStatusCode"]
        except Exception as err:
            logging.error(err)

    def upload(self, bucket_name, file_data, key_name, type):
        if type == 'stream':
            try:
                data = open(file_data, 'rb')
                self.s3.Bucket(bucket_name).put_object(Key=key_name, Body=data)
                logging.info("S3 stream object upload sucessfully!")
                return True
            except Exception as err:
                logging.error(err)
        elif type == 'file':
            try:
                self.s3.Bucket(bucket_name).upload_file(file_data, key_name)
                logging.info("S3 upload file sucessfully!")
                return True
            except Exception as err:
                logging.error(err)

    def download(self, bucket_name, key_name, file_path):
        try:
            bucket = self.s3.Bucket(bucket_name)
            bucket.download_file(key_name, file_path)
        except Exception as err:
            logging.error(err)

    def get_content(self, bucket_name, key_name):
        try:
            obj = self.s3.meta.client.get_object(Bucket=bucket_name, Key=key_name)
            results = obj['Body'].read()
            return results
        except Exception as err:
            logging.error(err)

